package token

import (
    "crypto/rsa"
	"github.com/dgrijalva/jwt-go"
	"io/ioutil"
	"time"
)
type MyCustomClaims struct {
	Id int64 `json:"id"`
	Name string `json:"name"`
	jwt.StandardClaims
}

func GenerateToken(id int64, name string, expireSecond int64) (string, int64, error) {
	//使用私钥生成token字符串
	privateKey := LoadRSAPrivateKeyFromDisk("token/private.pem")
	// Create the Claims
	var expiresAt = GetTimestamp() + expireSecond
	claims := MyCustomClaims{
		id,
		name,
		jwt.StandardClaims{
			ExpiresAt: expiresAt, //1h后过期
			Issuer:    "Cricket Auth Server",
		},
	}

	s := MakeSampleToken(claims, privateKey)
	return s, expiresAt, nil
}


func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey {
	keyData, e := ioutil.ReadFile(location)
	if e != nil {
		panic(e.Error())
	}
	key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData)
	if e != nil {
		panic(e.Error())
	}
	return key
}

func LoadRSAPublicKeyFromDisk(location string) *rsa.PublicKey {
	keyData, e := ioutil.ReadFile(location)
	if e != nil {
		panic(e.Error())
	}
	key, e := jwt.ParseRSAPublicKeyFromPEM(keyData)
	if e != nil {
		panic(e.Error())
	}
	return key
}

func MakeSampleToken(c jwt.Claims, key interface{}) string {
	token := jwt.NewWithClaims(jwt.SigningMethodRS256, c)
	s, e := token.SignedString(key)

	if e != nil {
		panic(e.Error())
	}

	return s
}

//return 1441006057 in sec
func GetTimestamp() int64 {
   return time.Now().Unix()
}
